package web;


import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

@WebListener
public class RequestLoggingListener implements ServletRequestListener {
    //创建logger实例
    private static final Logger logger = Logger.getLogger(RequestLoggingListener.class.getName());

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 在请求初始化时调用
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        // 获取请求的开始时间
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        // 从请求中获取客户端 IP、请求方法、请求 URI、查询字符串、User-Agent
        String clientIP = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");
        // 记录初始化时的日志，包含请求的关键信息
        logger.info(String.format("\nRequest Initialized:\n [Time: %d,\n Client IP: %s, \nMethod: %s,\n URI: %s,\n Query String: %s, \nUser-Agent: %s]",
                startTime, clientIP, method, uri, queryString != null ? queryString : "N/A", userAgent != null ? userAgent : "N/A"));
    }

    @Override
    // 在请求销毁时调用
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        // 获取请求开始时的时间
        long startTime = (Long) request.getAttribute("startTime");
        // 获取当前时间，计算处理请求所花费的时间
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
// 记录请求完成的日志，包含请求处理的时长
        logger.info(String.format("\nRequest Completed: [Duration: %d ms]", duration));
    }
}